import requests
import pytest
import json
import base64
import yaml
import os


class GetToken():
    @pytest.fixture(scope='session')
    def set_global_token(self):
        file_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'ym.yml'))
        with open(file_path, 'r') as file:
            data = yaml.safe_load(file)
            token = data.get('token')
        global TOKEN
        TOKEN = token
        yield TOKEN

    # # @pytest.fixture(scope="session")
    # def get_token(self):
    #     url = "https://www.test.carvingerp.com/python/v1/api/system/passport/login"
    #     json = {
    #         "uuid": "a29472c0-dca3-48d7-87a8-4dbf31e319af",
    #         "code": "ksxg",
    #         "company_name": "深圳市仕锦源科技有限公司",
    #         "account": "shenshaotian",
    #         "password": "shenshaotian"
    #     }
    #     r = requests.post(url=url, json=json)
    #     token = r.json()["data"]["token"]
    #     return token

    @pytest.fixture(scope="session")
    def get_api_profiler(self, set_global_token):
        url = "http://192.168.0.197:5000/v1/AmazonAd/AllProduct"
        headers = {
            "Authorization": TOKEN
        }
        params = {
            "profile_id": "192795951605339"
        }
        response1 = requests.get(url=url, params=params, headers=headers)
        assert response1.json()['code'] == 200
        data1 = response1.json()["data"][0]
        product_id = "16"
        if "product_id" in data1 and data1['product_id'] == product_id:
            str_obj = json.dumps(data1)
            encoded_data1 = base64.b64encode(str_obj.encode("utf-8")).decode("utf-8")
            return encoded_data1
        else:
            raise ValueError(f"Product ID {product_id} not found in the response data")
